// ConfigReader.cpp : simple config file reader
//
//	Author: Miroslav Hauser, hauz@students.zcu.cz
//	Version: 0.8
//
//	Reads simple config file allowing '#' comment and data are in <key>=<value>
//	format.
//
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

#include "ConfigReader.h"
#include "../GradeIface.h"

#include <string>
#include <fstream>
#include <sstream>

//	Character that will be used as a comment in config file. Lines containing
//	those characters at the beggining will be ignored.
static const char COMMENT_CHAR = '#';

using namespace std;

ConfigReader::ConfigReader(const char *fileName) {
	fIsRead = false;

	if (!ReadFile(fileName))
		throw "File could not be opened!";
}

bool ConfigReader::ReadFile(const char *fileName) {
	ifstream in(fileName);
	if (in.is_open() == false) {
		data.clear();		// clear map
		fIsRead = false;
		return fIsRead;
	} else {
		fIsRead = true;
	}

	string line;
	while (getline(in, line)) {
		if (line.size() == 0) { continue; }		// ignore blank lines
		Trim(&line);

		if (line.at(0) != COMMENT_CHAR) {		// skip comments
			int equalsPosition = line.find('=');
			string key = line.substr(0, equalsPosition);
			string value = line.substr(equalsPosition + 1, line.length() - 1);
			Trim(&key);
			Trim(&value);

			data.insert(pair<string, string>(key, value));
		}
	}
	in.close();


	return fIsRead;
}

void ConfigReader::GetKey(char *buf, const char *key) {
	string ret = data.find(key)->second;

	if (ret.size() >= MAX_VALUE_LEN)
		memcpy(buf, ret.c_str(), MAX_VALUE_LEN - 1);
	else
		memcpy(buf, ret.c_str(), ret.size() + 1);
}

map<string, string> ConfigReader::GetConfig() {
	return data;
}

bool ConfigReader::IsRead() {
	return fIsRead;
}

void ConfigReader::Trim(string *line) {
	// FIXME sure there is better way to do it. Maybe later :)

	// leading spaces
	while (line->at(0) == ' ') {
		line->erase(0, 1);
	}
	
	// trailing spaces
	while (line->at(line->size() - 1) == ' ') {
		line->erase(line->size() - 1);
	}
}